//
//  InputDataDetailViewController.m
//  RomensUISDK
//
//  Created by 裴飞杨 on 2018/9/14.
//  Copyright © 2018年 Romens. All rights reserved.
//

#import "InputDataDetailViewController.h"
#import "InputAddDataViewController.h"
#import <RomensSDK/SimpleBaseItem.h>
#import "InputDataDetailTVDelegate.h"
#import <RomensSDK/FormatUtil.h>
#import <RomensSDK/SimpleDataTable+OperateCategory.h>

@interface InputDataDetailViewController ()
@property (nonatomic, strong) UITableView *dataSetTableView;
@property (nonatomic, strong) InputDataDetailTVDelegate *delegate;
@property (nonatomic, strong) UIButton *addBtn;

@property (nonatomic, strong) SimpleDataTable *dataTable;
@property (nonatomic, copy) NSString *url;
@end

@implementation InputDataDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createDataSetViewUI];
    [self createNotification];
    [self requestDataByServer];
}
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark -UI
-(void)createDataSetViewUI {
    [self.mainBackGroundView addSubview:self.dataSetTableView];
    
    NSDictionary *views = NSDictionaryOfVariableBindings(_dataSetTableView);
    [self.mainBackGroundView addConstraints:[ToolHelper GetNSLayoutCont:views format:@"H:|[_dataSetTableView]|"]];
    NSArray *vConstraint;
    if (isEmptyString(self.templateCode)) {
        vConstraint = [ToolHelper GetNSLayoutCont:views format:@"V:|[_dataSetTableView]-|"];
    } else {
        [self.mainBackGroundView addSubview:self.addBtn];
        NSDictionary *views = NSDictionaryOfVariableBindings(_dataSetTableView, _addBtn);
        [self.mainBackGroundView addConstraints:[ToolHelper GetNSLayoutCont:views format:@"H:|-8-[_addBtn]-8-|"]];
        vConstraint = [ToolHelper GetNSLayoutCont:views format:@"V:|[_dataSetTableView]-[_addBtn(44)]-0-|"];
    }
    [self.mainBackGroundView addConstraints:vConstraint];
}

-(void)createNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestDataByServer) name:DATA_SELECT_LIST_RELOAD object:nil];
}

#pragma mark -完成事件触发
-(void)inputDone {
    NSString *nameStr = @"";
    for (NSDictionary *dict in self.dataTable.Data) {
        NSString *name = [ToolHelper isEmptyStr:dict[@"DRUGGENERICNAME"]];
        name = isEmptyString(name)? @" " : name;
        if (isEmptyString(nameStr)) {
            nameStr = [nameStr stringByAppendingString:name];
        } else {
            nameStr = [nameStr stringByAppendingString:[NSString stringWithFormat:@",%@", name]];
        }
    }
    self.inputDoneBlock(nameStr);
    [super inputDone];
}
#pragma mark -侧滑事件
-(void)editActionData:(SimpleBaseItem *)item type:(InputDataDetailTVActionsType)type {
    //删除
    if (type == InputDataDetailTVActionDelete) {
        __weak typeof(self)wSelf = self;
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确认删除" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [wSelf delegateData:item successBlock:^{
                [wSelf requestDataByServer];
            }];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertController addAction:okAction];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
        [self.dataSetTableView setEditing:NO animated:YES];
    }
    //编辑
    if (type == InputDataDetailTVActionEdit) {
        [self editActionData:item];
        [self.dataSetTableView setEditing:NO animated:YES];
    }
}
#pragma mark -编辑事件触发
-(void)editActionData:(SimpleBaseItem *)item {
    [self pushNextViewController:[self selectTouchItemGuid:item]];
}

#pragma mark -添加事件触发
-(void)addData {
    [self pushNextViewController:@""];
}
#pragma mark -跳转
-(void)pushNextViewController:(NSString *)guid {
    InputAddDataViewController *addDataVc = [[InputAddDataViewController alloc] init];
    addDataVc.templateCode = [ToolHelper isEmptyStr:self.templateCode];
    addDataVc.mainKey = [ToolHelper isEmptyStr:self.mainKey];
    addDataVc.guid = [ToolHelper isEmptyStr:guid];
    addDataVc.requestTemplateUrl = [ToolHelper isEmptyStr:self.url];
    addDataVc.defaultUrl = self.requestUrl;
    [self.navigationController pushViewController:addDataVc animated:YES];
}
#pragma mark -请求列表数据
-(void)requestDataByServer {
    __weak typeof(self)wSelf = self;
    [self Request: [ToolHelper isEmptyStr:self.url] queryType:[ToolHelper isEmptyStr:self.requestQueryType] postData:self.requestParames success:^(id respone) {
        WebRequestData *data = (WebRequestData*)respone;
        if (!isEmptyString(data.Error) || isEmptyString(data.RequestData)) {
            [wSelf showHint:isEmptyString(data.Error)? @"请求数据为空,请稍后再试！":data.Error  yOffset:-200];
            return;
        }
        id object = [ToolHelper JsonToDictionary:data.RequestData];
        if ([object isKindOfClass:[NSDictionary class]]) {
            SimpleDataTable *table = [[SimpleDataTable alloc] initWithKeyValues:((NSDictionary *)object)[@"DATA"]];
            wSelf.dataTable = table;
            [SimpleDataSpecialTemplateTool handleTemplateShowStyle:table];
            wSelf.delegate.dataArray = @[table];
            [wSelf.dataSetTableView reloadData];
        }
        
    } showHud:YES];
}
#pragma mark -删除单条数据
-(void)delegateData:(SimpleBaseItem *)item successBlock:(void(^)())block {
    NSString *guid = [self selectTouchItemGuid:item];
    if (isEmptyString(guid)) {
        [self showHint:@"删除失败!获取GUID失败"  yOffset:-200];
        return;
    }
    NSMutableDictionary *parames = [[NSMutableDictionary alloc] init];
    parames[@"GUID"] = guid;
    parames[@"TEMPLATECODE"] = self.templateCode;
    parames[@"DELETE_FLAG"] = @"1";
    __weak typeof(self)wSelf = self;
    [self Request:[ToolHelper isEmptyStr:self.url] queryType:@"updateUerDataSelectTemp" postData:parames success:^(id respone) {
        WebRequestData *data = (WebRequestData*)respone;
        if (!isEmptyString(data.Error) || isEmptyString(data.RequestData)) {
            [wSelf showHint:[NSString stringWithFormat:@"删除失败!原因：%@,请稍后再试！", isEmptyString(data.Error)? @"请求数据为空":data.Error]  yOffset:-200];
            return;
        }
        id object = [ToolHelper JsonToDictionary:data.RequestData];
        if ([object isKindOfClass:[NSDictionary class]]) {
            if ([((NSDictionary *)object)[@"DATA"] isEqualToString:@"1"]) {
                block();
                
            } else {
                [wSelf showHint:@"删除失败!"  yOffset:-200];
            }

        } else {
            [wSelf showHint:@"删除失败!返回数据不匹配"  yOffset:-200];
        }

    } showHud:YES];
}
#pragma mark -获取GUID
-(NSString *)selectTouchItemGuid:(SimpleBaseItem *)item {
    NSString *primaryKey = [self.dataTable selectExtra:@"PRIMARYKEY"];
    primaryKey = [FormatUtil stringReplacingEmptyStr:primaryKey brace:@"{}"];
    NSString *primaryValue = [ToolHelper isEmptyStr:item.rowData[primaryKey]];
    return [ToolHelper isEmptyStr:primaryValue];
}
#pragma mark -Lazy
-(UITableView *)dataSetTableView {
    if (!_dataSetTableView) {
        _dataSetTableView = [[UITableView alloc] init];
        _dataSetTableView.translatesAutoresizingMaskIntoConstraints = false;
        _dataSetTableView.tableFooterView = [[UIView alloc] init];
        _dataSetTableView.delegate = self.delegate;
        _dataSetTableView.dataSource = self.delegate;
    }
    return _dataSetTableView;
}
-(InputDataDetailTVDelegate *)delegate {
    if (!_delegate) {
        _delegate = [[InputDataDetailTVDelegate alloc] init];
        __weak typeof(self)wSelf = self;
        _delegate.didSelectItemBlock = ^(SimpleBaseItem *item) {
            [wSelf editActionData:item];
        };
        _delegate.actionBlock = ^(InputDataDetailTVActionsType actionType, SimpleBaseItem *item) {
            [wSelf editActionData:item type:actionType];
        };
    }
    return _delegate;
}
-(UIButton *)addBtn {
    if (!_addBtn) {
        _addBtn = [[UIButton alloc] init];
        _addBtn.translatesAutoresizingMaskIntoConstraints = false;
        [_addBtn setTitle:@"添加" forState:UIControlStateNormal];
        [_addBtn setBackgroundColor:SystemColor];
        [_addBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        _addBtn.layer.cornerRadius = 10.0;
        _addBtn.layer.masksToBounds = NO;
        [_addBtn addTarget:self action:@selector(addData) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}
-(NSString *)url {
    return [[ToolHelper isEmptyStr:self.requestUrl] stringByAppendingString:[ToolHelper isEmptyStr:self.requestHandler]];
}
-(NSMutableDictionary *)requestParames {
    if (!_requestParames) {
        _requestParames = [[NSMutableDictionary alloc] init];
    }
    return _requestParames;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
